export class VersionNotifierPoll {
    constructor (versionUrl, options = {}) {
        this.url = versionUrl;
        this.currentVersion = options.currentVersion || '';
        this.interval = options.interval || 10000; // 轮询间隔默认 10 秒
        this.timer = null;
        this.onUpdateCallback = null;
    }

    start() {
        this.timer = setInterval(async () => {
            try {
                const res = await fetch(this.url);
                const data = await res.json();
                if (data.version && data.version !== this.currentVersion) {
                    console.log(`📢 发现新版本 ${data.version}`);
                    if (this.onUpdateCallback) {
                        this.onUpdateCallback(data.version);
                    } else {
                        if (confirm(`检测到新版本 ${data.version}，是否刷新？`)) {
                            location.reload();
                        }
                    }
                }
            } catch (error) {
                console.warn('轮询获取版本失败:', error);
            }
        }, this.interval)
    }

    onUpdate(callback) {
        this.onUpdateCallback = callback;
    }

    stop() {
        if (this.timer) {
            clearInterval(this.timer)
            this.timer = null;
        }
    }
}